package com.adtech.adms.commons.web.intercepter;

import java.util.Map;

import com.adtech.adms.SessionKey;
import com.adtech.core.dao.query.Pager;
import com.adtech.core.dao.query.QueryConstants;
import com.adtech.core.dao.query.Sort;
import com.adtech.core.util.StringUtil;
import com.adtech.core.web.action.BaseAction;
import com.opensymphony.xwork2.ActionInvocation;

/**
 * 
 * 
 * @author Dormin 
 * @since 2011-6-8 
 * 
 * @Copyright (C) AD Tech Workshop All Right Reserved
 */
public class GridQueryInjectInterceptor extends BaseInterceptor {

	private static final long serialVersionUID = -6342795821580321655L;

	@Override
	public String intercept(ActionInvocation ai) throws Exception {
		Map<String, Object> params = super.getParameters(ai);
		if (ai.getAction() instanceof BaseAction) {
			BaseAction action = (BaseAction) ai.getAction();
			processPager(action, params);
			processSorter(action, params);
		}
		return ai.invoke();
	}

	private void processPager(BaseAction action, Map<String, Object> params) {
		Pager pager = new Pager(1, 10);
		// 当前页码
		if (params.get(SessionKey.PAGE_NUMBER) != null) {
			String[] values = (String[]) params.get(SessionKey.PAGE_NUMBER);
			if (values != null && values.length > 0 && !StringUtil.isEmpty(values[0])) {
				pager.setCurrentPage(Integer.parseInt(values[0]));
			}
		}
		// 每页行数
		if (params.get(SessionKey.PAGE_SIZE) != null) {
			String[] values = (String[]) params.get(SessionKey.PAGE_SIZE);
			if (values != null && values.length > 0 && !StringUtil.isEmpty(values[0])) {
				pager.setPageSize(Integer.parseInt(values[0]));
			}
		}

		action.setPager(pager);
	}

	private void processSorter(BaseAction action, Map<String, Object> params) {
		Sort sorter = new Sort();
		String sort = null;
		String order = QueryConstants.ASC;
		// 排序字段
		if (params.get(SessionKey.SORT) != null) {
			String[] values = (String[]) params.get(SessionKey.SORT);
			if (values != null && values.length > 0 && !StringUtil.isEmpty(values[0])) {
				sort = values[0];
			}
		}
		// 排序方式
		if (params.get(SessionKey.ORDER) != null) {
			String[] values = (String[]) params.get(SessionKey.ORDER);
			if (values != null && values.length > 0 && !StringUtil.isEmpty(values[0])) {
				order = values[0];
			}
		}
		if (sort != null) {
			sorter.addSort(sort, order);
			action.setSorter(sorter);
		}
	}

}
